const express = require('express');
const app = express();
const config = require("./config.json");
const service = require("./service/index.js");
const bodyParser = require('body-parser');
const WebSocketServer = require('ws').Server;
const http = require('http');


var server = http.createServer(app);
app.use(bodyParser());
app.use(express.static(__dirname + '/public'));
app.post('/api/upload', service.upload)
app.post('/api/sendmail', service.sendmail)


wss = new WebSocketServer({ server });
wss.on('connection', function (ws) {
    console.log('ws client connected');
    ws.on('message', function (message) {
        // console.log(message);
        service.sendmail(message, ws)
    });
    ws.on('close', function (close) {
        try {
            wss.broadcast(0);
        } catch (e) {
            console.log('ws client breaked!')
        }
    });
});


server.listen(config.port, () => {
    console.info("server start in :" + config.port)
});